Fetch 與 Promise (三):注意事項


Posted by s103071049 on 2021-07-10

一、Content Type

加在 headers,決定 server 要如何處理 request。通常要看 server 接收甚麼格式的資料,才能決定我的 content type 是甚麼。

server 會出錯,因為它無法解析你的資料。所以下面應該把 body 修正為 JSON.stringify(data)

fetch(api200, {
  method : 'POST',
  body: '123',
  headers: new Headers({
    'Content-Type': 'application/json'
  })
})

二、Credentials

如果發不是同個來源 domain 的 api (cross origin),如果我想要在發這類 request 將 cookie 一起帶上去,它的預設是不會將 cookie 帶上去。

所以,如果要將 cookie 跨 domain 也帶上去,要加上credentials: 'include'

fetch(api200, {
  method : 'POST',
  body: JSON.stringify(data),
  headers: new Headers({
    'Content-Type': 'application/json'
  }),
  credentials: 'include'
})

三、對 mode 的誤解

mode 有幾個值:cors, no-cors, *same-origin,似乎跟 Cross origin 有關。

現在發一個跨網域的 post 到 lidemy.com const api200 = 'https://lidemy.com'

出現 CORS 的錯誤,瀏覽器給予建議:If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.出現錯誤,因為 server 的 response 並沒有給予可以做 CORS 的 header。

依照建議直接加上,會發現原本的錯誤訊息不見了!

    fetch(api200, {
      method : 'POST',
      body: JSON.stringify(data),
      headers: new Headers({
        'Content-Type': 'application/json'
      }),
      mode: 'no-cors'
    })
      .then((response) => {
        console.log(response)
        return response.text()
      }).then(text => {
        console.log(text)
      }).catch(err => {
        console.log('err', err)
      })

此外,發現:text 是空的、response 出現了 type: "opaque" 且 status: 0。

意思是說在打 CORS 的 request,需要 server 有帶那個 header 才能拿到資料。就算我加了 mode: 'no-cors',server 還是必須要有那個 header。因為 server 沒有那個 header,所以我拿到的是空的 response。

mode: 'no-cors' 是說我知道 server 沒有提供 cors 的 header,但沒關係我本來就是要這樣做,我沒有要拿到 response,所以不用回傳錯誤給我,如果有這樣的情形,就給我一個成功的 response,不要跑到 catch error 去。

實際上因為 server 沒有開那個 header 給我,所以是不會收到來自 server 的 response

絕對不可能從 client 端突破 cors 的限制,mode: 'no-cors' 不是說加了就可以突破 cors 的限制。










Related Posts

OOCSS

OOCSS

關於 React 小書:做出 React

關於 React 小書:做出 React

簡單的 JS 陣列 method 整理

簡單的 JS 陣列 method 整理


Comments